from flask import Blueprint, jsonify, request
from sqlalchemy.sql.functions import random

from applications.models import Image
from applications.schemas import ImageSchema

bp = Blueprint('image', __name__, url_prefix='/image')

@bp.get('/random')
def image():
    data = Image.query.order_by(random()).limit(6)
    res = {
        "data": ImageSchema(many=True).dump(data)
    }
    return jsonify(res)

@bp.get('/<string:label>')
def getImageByClassify(label):
    pageNum = request.args.get('pageNum', type=int)
    pageSize = request.args.get('pageSize', type=int)
    # 计算LIMIT和OFFSET的值
    offset = pageSize * (pageNum - 1)
    data = Image.query.filter_by(label=label).limit(pageSize).offset(offset)
    res = {
        "data": ImageSchema(many=True).dump(data)
    }
    return jsonify(res)